package org.imperativetable;

import java.io.PrintWriter;
import java.io.Writer;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.imperativetable.render.CsvTableRenderer;
import org.imperativetable.render.HtmlTableRenderer;
import org.imperativetable.render.TableRenderer;
import org.imperativetable.render.XmlTableRenderer;

public class Renderer {

    private static final Map<String, TableRenderer> RENDERERS;

    static {
        Map<String, TableRenderer> renderers = new HashMap<String, TableRenderer>();
        TableRenderer htmlTableRenderer = new HtmlTableRenderer();
        renderers.put(null, htmlTableRenderer);
        renderers.put(TableRenderer.HTML_FORMAT, htmlTableRenderer);
        renderers.put(TableRenderer.CSV_FORMAT, new CsvTableRenderer());
        renderers.put(TableRenderer.XML_FORMAT, new XmlTableRenderer());
        RENDERERS = Collections.unmodifiableMap(renderers);
    }

    ;

    private Renderer() {
        throw new Error("Attempt to create Renderer instance was maid!");
    }

    public static void render(HttpServletRequest request, Writer writer, Table table) {
        PrintWriter out = new PrintWriter(writer);

        if (request.getParameter(TableRenderer.SORTED_COLUMN_PARAMETER_NAME) != null) {
            try {
                Integer sortedColumn = Integer.parseInt(request.getParameter(TableRenderer.SORTED_COLUMN_PARAMETER_NAME));
                table.setSortedColumn(sortedColumn.intValue());
            } catch (NumberFormatException e) {
                out.println("[ERROR in \"it_sort_column\" parameter value]");
                return;
            }
        }

        if (request.getParameter(TableRenderer.SORTED_ORDER_PARAMETER_NAME) != null) {
            if (TableRenderer.SORT_ORDER_ASCENDING.equals(request.getParameter(TableRenderer.SORTED_ORDER_PARAMETER_NAME))) {
                table.setSortOrderAscending();
            } else if (TableRenderer.SORT_ORDER_DESCENDING.equals(request.getParameter(TableRenderer.SORTED_ORDER_PARAMETER_NAME))) {
                table.setSortOrderDescending();
            } else {
                out.println("[ERROR in \"it_sort_order\" parameter value]");
                return;
            }
        }

        if (request.getParameter(TableRenderer.PAGE_PARAMETER_NAME) != null) {
            try {
                Integer currentPage = Integer.parseInt(request.getParameter(TableRenderer.PAGE_PARAMETER_NAME));
                table.setCurrentPage(currentPage.intValue());
            } catch (NumberFormatException e) {
                out.println("[ERROR in \"it_page\" parameter value]");
                return;
            }
        }

        RENDERERS.get(request.getParameter(TableRenderer.FORMAT_PARAMETER_NAME)).render(writer, table);
    }
}
